/*
 * Copyright (c) 2017 Simon Goldschmidt
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
 * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
 * OF SUCH DAMAGE.
 *
 * This file is part of the lwIP TCP/IP stack.
 *
 * Author: Simon Goldschmidt <goldsimon@gmx.de>
 *
 */

/* lwIP includes. */
#include "lwip/debug.h"
#include "lwip/def.h"
#include "lwip/sys.h"
#include "lwip/mem.h"
#include "lwip/stats.h"
#include "lwip/tcpip.h"
#include <rtthread.h>
#include <rthw.h>

// /** Set this to 1 if you want the stack size passed to sys_thread_new() to be
//  * interpreted as number of stack words (FreeRTOS-like).
//  * Default is that they are interpreted as byte count (lwIP-like).
//  */
// #ifndef LWIP_FREERTOS_THREAD_STACKSIZE_IS_STACKWORDS
// #define LWIP_FREERTOS_THREAD_STACKSIZE_IS_STACKWORDS  0
// #endif

// /** Set this to 1 to use a mutex for SYS_ARCH_PROTECT() critical regions.
//  * Default is 0 and locks interrupts/scheduler for SYS_ARCH_PROTECT().
//  */
// #ifndef LWIP_FREERTOS_SYS_ARCH_PROTECT_USES_MUTEX
// #define LWIP_FREERTOS_SYS_ARCH_PROTECT_USES_MUTEX     0
// #endif

// /** Set this to 1 to include a sanity check that SYS_ARCH_PROTECT() and
//  * SYS_ARCH_UNPROTECT() are called matching.
//  */
// #ifndef LWIP_FREERTOS_SYS_ARCH_PROTECT_SANITY_CHECK
// #define LWIP_FREERTOS_SYS_ARCH_PROTECT_SANITY_CHECK   0
// #endif

// /** Set this to 1 to let sys_mbox_free check that queues are empty when freed */
// #ifndef LWIP_FREERTOS_CHECK_QUEUE_EMPTY_ON_FREE
// #define LWIP_FREERTOS_CHECK_QUEUE_EMPTY_ON_FREE       0
// #endif

// /** Set this to 1 to enable core locking check functions in this port.
//  * For this to work, you'll have to define LWIP_ASSERT_CORE_LOCKED()
//  * and LWIP_MARK_TCPIP_THREAD() correctly in your lwipopts.h! */
// #ifndef LWIP_FREERTOS_CHECK_CORE_LOCKING
// #define LWIP_FREERTOS_CHECK_CORE_LOCKING              0
// #endif

// /** Set this to 0 to implement sys_now() yourself, e.g. using a hw timer.
//  * Default is 1, where FreeRTOS ticks are used to calculate back to ms.
//  */
// #ifndef LWIP_FREERTOS_SYS_NOW_FROM_FREERTOS
// #define LWIP_FREERTOS_SYS_NOW_FROM_FREERTOS           1
// #endif

//#if !configSUPPORT_DYNAMIC_ALLOCATION
//# error "lwIP FreeRTOS port requires configSUPPORT_DYNAMIC_ALLOCATION"
//#endif
//#if !INCLUDE_vTaskDelay
//# error "lwIP FreeRTOS port requires INCLUDE_vTaskDelay"
//#endif
//#if !INCLUDE_vTaskSuspend
//# error "lwIP FreeRTOS port requires INCLUDE_vTaskSuspend"
//#endif
//#if LWIP_FREERTOS_SYS_ARCH_PROTECT_USES_MUTEX || !LWIP_COMPAT_MUTEX
//#if !configUSE_MUTEXES
//# error "lwIP FreeRTOS port requires configUSE_MUTEXES"
//#endif
//#endif

//#if SYS_LIGHTWEIGHT_PROT && LWIP_FREERTOS_SYS_ARCH_PROTECT_USES_MUTEX
//static SemaphoreHandle_t sys_arch_protect_mutex;
//#endif
//#if SYS_LIGHTWEIGHT_PROT && LWIP_FREERTOS_SYS_ARCH_PROTECT_SANITY_CHECK
//static sys_prot_t sys_arch_protect_nesting;
//#endif

/* Initialize this module (see description in sys.h) */
void
sys_init(void)
{
#if SYS_LIGHTWEIGHT_PROT && LWIP_FREERTOS_SYS_ARCH_PROTECT_USES_MUTEX
  /* initialize sys_arch_protect global mutex */
  sys_arch_protect_mutex = xSemaphoreCreateRecursiveMutex();
  LWIP_ASSERT("failed to create sys_arch_protect mutex",
    sys_arch_protect_mutex != NULL);
#endif /* SYS_LIGHTWEIGHT_PROT && LWIP_FREERTOS_SYS_ARCH_PROTECT_USES_MUTEX */
}

#if configUSE_16_BIT_TICKS == 1
#error This port requires 32 bit ticks or timer overflow will fail
#endif

//rt_tick_t rt_tick_get_millisecond(void)
//{
//#if 1000 % RT_TICK_PER_SECOND == 0u
//    return rt_tick_get() * (1000u / RT_TICK_PER_SECOND);
//#else
//    #warning "rt-thread cannot provide a correct 1ms-based tick any longer,\
//    please redefine this function in another file by using a high-precision hard-timer."
//    return 0;
//#endif /* 1000 % RT_TICK_PER_SECOND == 0u */
//}

u32_t
sys_now(void)
{
  //return rt_tick_get_millisecond();
	return rt_tick_get();
}


u32_t
sys_jiffies(void)
{
  return rt_tick_get();
}

#if SYS_LIGHTWEIGHT_PROT

sys_prot_t
sys_arch_protect(void)
{
#if LWIP_FREERTOS_SYS_ARCH_PROTECT_USES_MUTEX
  BaseType_t ret;
  LWIP_ASSERT("sys_arch_protect_mutex != NULL", sys_arch_protect_mutex != NULL);

  ret = xSemaphoreTakeRecursive(sys_arch_protect_mutex, portMAX_DELAY);
  LWIP_ASSERT("sys_arch_protect failed to take the mutex", ret == pdTRUE);
#else /* LWIP_FREERTOS_SYS_ARCH_PROTECT_USES_MUTEX */
  taskENTER_CRITICAL();
#endif /* LWIP_FREERTOS_SYS_ARCH_PROTECT_USES_MUTEX */
#if LWIP_FREERTOS_SYS_ARCH_PROTECT_SANITY_CHECK
  {
    /* every nested call to sys_arch_protect() returns an increased number */
    sys_prot_t ret = sys_arch_protect_nesting;
    sys_arch_protect_nesting++;
    LWIP_ASSERT("sys_arch_protect overflow", sys_arch_protect_nesting > ret);
    return ret;
  }
#else
  return 1;
#endif
}

void
sys_arch_unprotect(sys_prot_t pval)
{
#if LWIP_FREERTOS_SYS_ARCH_PROTECT_USES_MUTEX
  BaseType_t ret;
#endif
#if LWIP_FREERTOS_SYS_ARCH_PROTECT_SANITY_CHECK
  LWIP_ASSERT("unexpected sys_arch_protect_nesting", sys_arch_protect_nesting > 0);
  sys_arch_protect_nesting--;
  LWIP_ASSERT("unexpected sys_arch_protect_nesting", sys_arch_protect_nesting == pval);
#endif

#if LWIP_FREERTOS_SYS_ARCH_PROTECT_USES_MUTEX
  LWIP_ASSERT("sys_arch_protect_mutex != NULL", sys_arch_protect_mutex != NULL);

  ret = xSemaphoreGiveRecursive(sys_arch_protect_mutex);
  LWIP_ASSERT("sys_arch_unprotect failed to give the mutex", ret == pdTRUE);
#else /* LWIP_FREERTOS_SYS_ARCH_PROTECT_USES_MUTEX */
  taskEXIT_CRITICAL();
#endif /* LWIP_FREERTOS_SYS_ARCH_PROTECT_USES_MUTEX */
  LWIP_UNUSED_ARG(pval);
}

#endif /* SYS_LIGHTWEIGHT_PROT */

void
sys_arch_msleep(u32_t delay_ms)
{
  rt_thread_mdelay(delay_ms);
}

#if !LWIP_COMPAT_MUTEX

/* Create a new mutex*/
err_t
sys_mutex_new(sys_mutex_t *mutex)
{
  static unsigned short counter = 0;
    char tname[RT_NAME_MAX];
    sys_mutex_t tmpmutex;

    RT_DEBUG_NOT_IN_INTERRUPT;

    rt_snprintf(tname, RT_NAME_MAX, "%s%d", SYS_LWIP_MUTEX_NAME, counter);
    counter ++;

    tmpmutex.mut = rt_mutex_create(tname, RT_IPC_FLAG_PRIO);
    if (tmpmutex.mut == RT_NULL)
    {
        return ERR_MEM;
    }
    else
    {
        *mutex = tmpmutex;
        return ERR_OK;
    }
}

void
sys_mutex_lock(sys_mutex_t *mutex)
{
  RT_DEBUG_NOT_IN_INTERRUPT;
    rt_mutex_take(mutex->mut, RT_WAITING_FOREVER);

}

void
sys_mutex_unlock(sys_mutex_t *mutex)
{
  rt_mutex_release(mutex->mut);
}

void
sys_mutex_free(sys_mutex_t *mutex)
{
  RT_DEBUG_NOT_IN_INTERRUPT;
    rt_mutex_delete(mutex->mut);
}

//#ifndef sys_mutex_valid
/** Check if a mutex is valid/allocated:
 *  return 1 for valid, 0 for invalid
 */
int sys_mutex_valid(sys_mutex_t *mutex)
{
    return (int)(mutex->mut);
}
void sys_mutex_set_invalid(sys_mutex_t *mutex)
{
    mutex->mut = RT_NULL;
}
//#endif

#endif /* !LWIP_COMPAT_MUTEX */

err_t
sys_sem_new(sys_sem_t *sem, u8_t initial_count)
{
  static unsigned short counter = 0;
    char tname[RT_NAME_MAX];
    sys_sem_t tmpsem;

    RT_DEBUG_NOT_IN_INTERRUPT;

    rt_snprintf(tname, RT_NAME_MAX, "%s%d", SYS_LWIP_SEM_NAME, counter);
    counter ++;

    tmpsem.sem = rt_sem_create(tname, initial_count, RT_IPC_FLAG_FIFO);
    if (tmpsem.sem == RT_NULL)
    {
        return ERR_MEM;
    }
    else
    {
        *sem = tmpsem;

        return ERR_OK;
    }
}

void
sys_sem_signal(sys_sem_t *sem)
{
  rt_sem_release(sem->sem);
}

u32_t
sys_arch_sem_wait(sys_sem_t *sem, u32_t timeout_ms)
{
  rt_err_t ret;
    s32_t t;
    u32_t tick;

    RT_DEBUG_NOT_IN_INTERRUPT;

    /* get the begin tick */
    tick = rt_tick_get();
    if (timeout_ms == 0)
    {
        t = RT_WAITING_FOREVER;
    }
    else
    {
        /* convert msecond to os tick */
        if (timeout_ms < (1000 / RT_TICK_PER_SECOND))
            t = 1;
        else
            t = timeout_ms / (1000 / RT_TICK_PER_SECOND);
    }

    ret = rt_sem_take(sem->sem, t);

    if (ret == -RT_ETIMEOUT)
    {
        return SYS_ARCH_TIMEOUT;
    }
    else
    {
        if (ret == RT_EOK)
            ret = 1;
    }

    /* get elapse msecond */
    tick = rt_tick_get() - tick;

    /* convert tick to msecond */
    tick = tick * (1000 / RT_TICK_PER_SECOND);
    if (tick == 0)
        tick = 1;

    return tick;
}

void
sys_sem_free(sys_sem_t *sem)
{
  RT_DEBUG_NOT_IN_INTERRUPT;
    rt_sem_delete(sem->sem);
}

int sys_sem_valid(sys_sem_t *sem)
{
    return (int)(sem->sem);
}

void sys_sem_set_invalid(sys_sem_t *sem)
{
    sem->sem = RT_NULL;
}

err_t
sys_mbox_new(sys_mbox_t *mbox, int size)
{
  static unsigned short counter = 0;
    char tname[RT_NAME_MAX];
    sys_mbox_t tmpmbox;

    RT_DEBUG_NOT_IN_INTERRUPT;

    rt_snprintf(tname, RT_NAME_MAX, "%s%d", SYS_LWIP_MBOX_NAME, counter);
    counter ++;

    tmpmbox.mbx = rt_mb_create(tname, size, RT_IPC_FLAG_FIFO);
    if (tmpmbox.mbx != RT_NULL)
    {
        *mbox = tmpmbox;

        return ERR_OK;
    }

    return ERR_MEM;
}

void
sys_mbox_post(sys_mbox_t *mbox, void *msg)
{
  RT_DEBUG_NOT_IN_INTERRUPT;
    rt_mb_send_wait(mbox->mbx, (rt_ubase_t)msg, RT_WAITING_FOREVER);
    return;
}

err_t
sys_mbox_trypost(sys_mbox_t *mbox, void *msg)
{
  if (rt_mb_send(mbox->mbx, (rt_ubase_t)msg) == RT_EOK)
    {
        return ERR_OK;
    }

    return ERR_MEM;
}

//#if (LWIP_VERSION_MAJOR * 100 + LWIP_VERSION_MINOR) >= 201 /* >= v2.1.0 */
err_t
sys_mbox_trypost_fromisr(sys_mbox_t *mbox, void *msg)
{
  return sys_mbox_trypost(mbox, msg);
}
//#endif /* (LWIP_VERSION_MAJOR * 100 + LWIP_VERSION_MINOR) >= 201 */

u32_t
sys_arch_mbox_fetch(sys_mbox_t *mbox, void **msg, u32_t timeout_ms)
{
  rt_err_t ret;
    s32_t t;
    u32_t tick;

    RT_DEBUG_NOT_IN_INTERRUPT;

    /* get the begin tick */
    tick = rt_tick_get();

    if(timeout_ms == 0)
    {
        t = RT_WAITING_FOREVER;
    }
    else
    {
        /* convirt msecond to os tick */
        if (timeout_ms < (1000 / RT_TICK_PER_SECOND))
            t = 1;
        else
            t = timeout_ms / (1000 / RT_TICK_PER_SECOND);
    }

    ret = rt_mb_recv(mbox->mbx, (rt_ubase_t *)msg, t);
    if(ret != RT_EOK)
    {
        return SYS_ARCH_TIMEOUT;
    }

    /* get elapse msecond */
    tick = rt_tick_get() - tick;

    /* convert tick to msecond */
    tick = tick * (1000 / RT_TICK_PER_SECOND);
    if (tick == 0)
        tick = 1;

    return tick;
}

u32_t
sys_arch_mbox_tryfetch(sys_mbox_t *mbox, void **msg)
{
  int ret;

    ret = rt_mb_recv(mbox->mbx, (rt_ubase_t *)msg, 0);
    if(ret == -RT_ETIMEOUT)
    {
        return SYS_ARCH_TIMEOUT;
    }
    else
    {
        if (ret == RT_EOK)
            ret = 0;
    }

    return ret;
}

void
sys_mbox_free(sys_mbox_t *mbox)
{
  RT_DEBUG_NOT_IN_INTERRUPT;
    rt_mb_delete(mbox->mbx);
    return;
}

int sys_mbox_valid(sys_mbox_t *mbox)
{
    return (int)(mbox->mbx);
}

void sys_mbox_set_invalid(sys_mbox_t *mbox)
{
    mbox->mbx = RT_NULL;
}

sys_thread_t
sys_thread_new(const char *name, lwip_thread_fn thread, void *arg, int stacksize, int prio)
{
	sys_thread_t sys_thread;
  rt_thread_t t;
	sys_thread.thread_handle = t;

    RT_DEBUG_NOT_IN_INTERRUPT;

    /* create thread */
    t = rt_thread_create(name, thread, arg, stacksize, prio, 20);
    RT_ASSERT(t != RT_NULL);

    /* startup thread */
    rt_thread_startup(t);

    return sys_thread;
}

sys_prot_t sys_arch_protect(void)
{
    rt_base_t level;
    level = rt_hw_interrupt_disable(); /* disable interrupt */
    return level;
}

void sys_arch_unprotect(sys_prot_t pval)
{
    rt_hw_interrupt_enable(pval); /* enable interrupt */
}

void sys_arch_assert(const char *file, int line)
{
    rt_kprintf("\nAssertion: %d in %s, thread %s\n",
               line, file, rt_thread_self()->name);
    RT_ASSERT(0);
}

RT_WEAK void mem_init(void)
{
}

void gettimeofday(struct timeval *tv, void *tz) {
    // 这里只是一个示例实现，实际使用时需要根据硬件的具体时钟系统来实现。
    // 例如，使用 SysTick 的计数来模拟。
    tv->tv_sec = 0; // 示例值，需要替换为实际的时间获取逻辑
    tv->tv_usec = 0; // 示例值，需要替换为实际的时间获取逻辑
}
//void *mem_calloc(mem_size_t count, mem_size_t size)
//{
//    return rt_calloc(count, size);
//}

//void *mem_trim(void *mem, mem_size_t size)
//{
//    // return rt_realloc(mem, size);
//    /* not support trim yet */
//    return mem;
//}

//void *mem_malloc(mem_size_t size)
//{
//    return rt_malloc(size);
//}

//void  mem_free(void *mem)
//{
//    rt_free(mem);
//}

#if LWIP_NETCONN_SEM_PER_THREAD
#if configNUM_THREAD_LOCAL_STORAGE_POINTERS > 0

sys_sem_t *
sys_arch_netconn_sem_get(void)
{
  void* ret;
  TaskHandle_t task = xTaskGetCurrentTaskHandle();
  LWIP_ASSERT("task != NULL", task != NULL);

  ret = pvTaskGetThreadLocalStoragePointer(task, 0);
  return ret;
}

void
sys_arch_netconn_sem_alloc(void)
{
  void *ret;
  TaskHandle_t task = xTaskGetCurrentTaskHandle();
  LWIP_ASSERT("task != NULL", task != NULL);

  ret = pvTaskGetThreadLocalStoragePointer(task, 0);
  if(ret == NULL) {
    sys_sem_t *sem;
    err_t err;
    /* need to allocate the memory for this semaphore */
    sem = mem_malloc(sizeof(sys_sem_t));
    LWIP_ASSERT("sem != NULL", sem != NULL);
    err = sys_sem_new(sem, 0);
    LWIP_ASSERT("err == ERR_OK", err == ERR_OK);
    LWIP_ASSERT("sem invalid", sys_sem_valid(sem));
    vTaskSetThreadLocalStoragePointer(task, 0, sem);
  }
}

void sys_arch_netconn_sem_free(void)
{
  void* ret;
  TaskHandle_t task = xTaskGetCurrentTaskHandle();
  LWIP_ASSERT("task != NULL", task != NULL);

  ret = pvTaskGetThreadLocalStoragePointer(task, 0);
  if(ret != NULL) {
    sys_sem_t *sem = ret;
    sys_sem_free(sem);
    mem_free(sem);
    vTaskSetThreadLocalStoragePointer(task, 0, NULL);
  }
}

#else /* configNUM_THREAD_LOCAL_STORAGE_POINTERS > 0 */
#error LWIP_NETCONN_SEM_PER_THREAD needs configNUM_THREAD_LOCAL_STORAGE_POINTERS
#endif /* configNUM_THREAD_LOCAL_STORAGE_POINTERS > 0 */

#endif /* LWIP_NETCONN_SEM_PER_THREAD */

//#if LWIP_FREERTOS_CHECK_CORE_LOCKING

//#if !NO_SYS
//static TaskHandle_t lwip_tcpip_thread;
//#endif

//void
//sys_mark_tcpip_thread(void)
//{
//#if !NO_SYS
//  lwip_tcpip_thread = xTaskGetCurrentTaskHandle();
//#endif
//}

//void
//sys_check_core_locking(void)
//{
//  /* Embedded systems should check we are NOT in an interrupt context here */
//  /* E.g. core Cortex-M3/M4 ports:
//         configASSERT( ( portNVIC_INT_CTRL_REG & portVECTACTIVE_MASK ) == 0 );

//     Instead, we use more generic FreeRTOS functions here, which should fail from ISR: */
//  taskENTER_CRITICAL();
//  taskEXIT_CRITICAL();

//#if !NO_SYS
//  if (lwip_tcpip_thread != 0) {
//    TaskHandle_t current_thread = xTaskGetCurrentTaskHandle();

//#if LWIP_TCPIP_CORE_LOCKING
//    LWIP_ASSERT("Function called without core lock",
//                current_thread == lwip_core_lock_holder_thread && lwip_core_lock_count > 0);
//#else /* LWIP_TCPIP_CORE_LOCKING */
//    LWIP_ASSERT("Function called from wrong thread", current_thread == lwip_tcpip_thread);
//#endif /* LWIP_TCPIP_CORE_LOCKING */
//  }
//#endif /* !NO_SYS */
//}

//#endif /* LWIP_FREERTOS_CHECK_CORE_LOCKING*/
